let Vue;

class VueRouter {
  constructor(options) {
    this.$options = options
    this.current = window.location.hash.slice(1) || '/'
    console.log(this.current, '111')
    Vue.util.defineReactive(this, 'matched', [])
    this.match()
    addEventListener("hashchange", () => {
      this.current = window.location.hash.slice(1);
      this.matched = [];
      this.match();
    });
  }

  match(routes) {
    routes = routes || this.$options.routes;
    console.log(routes, '444')
    for (const route of routes) {
      if (route.path === "/" && this.current === "/") {
        this.matched.push(route);
        return;
      }
      if (route.path !== "/" && this.current.indexOf(route.path) !== -1) {
        this.matched.push(route);
        if (route.children) this.match(route.children);
      }
    }
  }

}

VueRouter.install = function (_vue) {
  Vue = _vue;
  Vue.mixin({
    beforeCreate() {
      if (this.$options.router) {
        Vue.prototype.$router = this.$options.router
      }
    }
  })

  Vue.component('router-link', {
    props: {
      to: {
        type: String,
        require: true
      }
    },
    render(h) {
      return h(
        'a',
        {
          attrs: {
            href: '#' + this.to
          },
        },
        this.$slots.default
      )
    }
  })

  Vue.component('router-view', {
    render(h) {
      this.$vnode.data.routerView = true
      let parent = this.$parent
      let depth = 0
      while (parent) {
        let vnodeData = parent.$vnode && parent.$vnode.data
        if (vnodeData && vnodeData.routerView) {
          depth++
        }
        parent = parent.$parent
      }
      let component = null
      let router = this.$router.matched[depth]
      if (router) component = router.component
      // console.log(this.$router)
      return h(component)
    }
  })
}

export default VueRouter
